(function () {
})();
var logo_color=window.localStorage.getItem('layuiAdmin')?JSON.parse(window.localStorage.getItem('layuiAdmin')).theme.color.logo:'#F78400';
$('.layui-tab-title').attr('style','border-color:'+logo_color);
$('.layui-tab-title li').attr('style','background-color:none;color:#666666');
$('.layui-tab-title .layui-this').attr('style','color:#fff;background-color:'+logo_color);
//Tab选项卡修改背景颜色
$(document).on('click', '.layui-tab-title', function (event) {
    $('.layui-tab-title').attr('style','border-color:'+logo_color);
	$('.layui-tab-title li').attr('style','background-color:none;color:#666666');
	$('.layui-tab-title .layui-this').attr('style','color:#fff;background-color:'+logo_color);
})
//数值框输入限制大小
$("input[type='number']").blur(function(obj){
	if(!!obj.currentTarget.min && obj.currentTarget.value<obj.currentTarget.min)obj.currentTarget.value=obj.currentTarget.min;
	if(!!obj.currentTarget.max && obj.currentTarget.value>obj.currentTarget.max)obj.currentTarget.value=obj.currentTarget.max;
})
//tree表格树 展开/折叠
var expandFlag;
$("#expandAllBtn").click(function() {
	var dataExpand = $.common.isEmpty($.tablelist._option.expandAll) ? true : $.tablelist._option.expandAll;
	expandFlag = $.common.isEmpty(expandFlag) ? dataExpand : expandFlag;
    if (!expandFlag) {
    	$.bttTable.bootstrapTreeTable('expandAll');
    } else {
    	$.bttTable.bootstrapTreeTable('collapseAll');
    }
    expandFlag = expandFlag ? false: true;
});
//获取当前时间
function getTime() {
	var newDate = new Date;
    var year = newDate.getFullYear();	//获取当前年
    var mon = newDate.getMonth() + 1;	//获取当前月
    var date = newDate.getDate();		//获取当前日
    var h = newDate.getHours();			//获取当前小时数(0-23)
    var m = newDate.getMinutes();		//获取当前分钟数(0-59)
    var s = newDate.getSeconds();		//获取当前秒
    var week = newDate.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    return year + "-" + appendZero(mon) + "-" + appendZero(date) + " "+ appendZero(h) + ":" + appendZero(m) + ":" + appendZero(s);
}
//转化时间格式
function formatDate(dateTime) {
    var year = dateTime.getFullYear();	//获取当前年
    var mon = dateTime.getMonth() + 1;	//获取当前月
    var date = dateTime.getDate();		//获取当前日
    var h = dateTime.getHours();		//获取当前小时数(0-23)
    var m = dateTime.getMinutes();		//获取当前分钟数(0-59)
    var s = dateTime.getSeconds();		//获取当前秒
    var week = dateTime.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    return year + "-" + appendZero(mon) + "-" + appendZero(date) + " "+ appendZero(h) + ":" + appendZero(m) + ":" + appendZero(s);
}
//时间相关——补全两位数
function appendZero (obj) {
	if (obj < 10) return "0" + obj; else return obj;
}
//"10/1/19" 转 "2019-10-01"
function forDate(d){
	var date = new Date(d);
	return date.getFullYear() + "-" + ((parseInt(date.getMonth()) + 1  > 9) ? (parseInt(date.getMonth()) + 1) : "0" + (parseInt(date.getMonth()) + 1)) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate());
}
//序列化表单字段为json对象
$.fn.serializeFormToJson = function(){
	var arr = $(this).serializeArray();//form表单数据 name：value
	var param = {};
	$.each(arr,function(i,obj){ //将form表单数据封装成json对象
		param[obj.name] = obj.value;
	})
	return param;
}
//弹出列设置框、操作
function filedSet(moduleTable){
	layer.config({
	  extend: 'myskin/style.css', //加载扩展样式
	});
	layer.open({
		type: 2,
		skin:'reset-class',
		area: ['620px', '550px'],
		offset: '6%',//距离顶部
		fix: false,
		maxmin: true,
		shade: 0.6,
		title: '列设置',
		content: '/system/userdefinedfields?moduleTable='+moduleTable,
		btn: ['确定', '重置', '关闭'],
		shadeClose: true,
		yes: function(index){
	    	var res = window["layui-layer-iframe" + index].callbackdata();
				$.operate.post('/system/userdefinedfields/editpost',{'infoItems':JSON.stringify(res),'moduleTable':moduleTable},function(result){
	    		setTimeout(function(){
	                window.location.reload();
	            }, 1500);
			});
	 	}
		,btn2: function(index, layero){
			$.modal.confirmCom('确认要恢复系统设置（删除用户自定义设置列）吗？', function(index){
				$.operate.post('/system/userdefinedfields/resetpost',{'moduleTable':moduleTable},function(result){
		    		setTimeout(function(){
		                window.location.reload();
		            }, 1500);
				});
			});
			return false;
 	    },
	    cancel: function(index) {
	        return true;
	    }
	});
	/*$.modal.open('列设置','/system/userdefinedfields?moduleTable='+moduleTable,'620','550',function(index){
    	var res = window["layui-layer-iframe" + index].callbackdata();
			$.operate.post('/system/userdefinedfields/editpost',{'infoItems':JSON.stringify(res),'moduleTable':moduleTable},function(result){
    		setTimeout(function(){
                window.location.reload();
            }, 1500);
		});
 	}) */
}
//添加搜索条件
function addMore(obj){
	appendSearch(obj,1);
	//删除条件
	$(".remove-this").click(function(){
		$(this).parents('.layui-col-xs3').remove();
	})
}
/*
 * 生成查询条件代码
 * param:obj 下拉对象
 * param:where 添加位置（1：顶部、2：右侧）
 */
function appendSearch(obj,where){
	var select=$('#condition option:selected');
	var key=select.val().replace(select.val()[0],select.val()[0].toLowerCase());//首字母小写
//    	if(key.substring(key.length-4,key.length)=='Name')key=key.substring(0,key.length-4);//虚拟字段切割？客户属性、供应商属性
	if(document.getElementById(key)){//通过id查找是否存在相同id
		layer.msg("该查询条件已存在！");
		return;
	}
	switch(where){//判断添加位置
		case 1://顶部（xs3样式）
			wherestr[key]='';//给该条件的查询语句占坑
			var str = "<div class='layui-inline layui-col-xs3'><label class='layui-form-label'>"+ select.text() +"：</label><div class='layui-input-block'>";
			break;
		case 2://右侧（查询列表）
			if(select.attr('fft') == 't_text' && select.attr('ffct') == 't_between'){
				var str = "<div class='layui-form-item item-height'><label class='layui-form-label'>"+ select.text() +"从：</label><div class='layui-input-block'>";	
			}else{
				var str = "<div class='layui-form-item'><label class='layui-form-label'>"+ select.text() +"：</label><div class='layui-input-block'>";	
			}
			break;
		default:
			layer.msg("添加位置参数为空！");
			break;
	}
	switch(select.attr('fft')){
		case 't_text'://文本输入框
			if(select.attr('ffct') != 't_between'){
    			str += "<input type='text' name='"+ key +"' id='"+key+"' autocomplete='off' class='layui-input search-field' fft='t_text'><a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			}else{
    			str += "<input type='text' name='"+ key +"_s' id='"+key+"_s' autocomplete='off' class='layui-input search-field' fft='t_text'><a class='fa fa-times-circle-o remove-this' style='margin-top: -7px;'>&nbsp;</a></div>";    	
    			str += "<label class='layui-form-label'>到：</label><div class='layui-input-block'>";
   				str += "<input type='text' name='"+ key +"_e' id='"+key+"_e' autocomplete='off' class='layui-input search-field' fft='t_text'></div></div>";
			}
			break;
		case 't_date'://日期选择框
			str +="<input type='text' class='layui-input search-field' id='"+ key +"' name='"+key+"' autocomplete='off' placeholder='请选择时间范围' fft='t_date' ffct='"+select.attr('ffct')+"'>";
			str +="<i class='fa fa-calendar icon_date_business'></i><a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			break;
		case 't_month'://年月选择框
			str +="<input type='text' class='layui-input search-field' id='"+ key +"' name='"+key+"' autocomplete='off' placeholder='请选择时间范围' fft='t_month' ffct='"+select.attr('ffct')+"'>";
			str +="<i class='fa fa-calendar icon_date_business'></i><a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			break;
		case 't_datetime'://日期时间选择框
			str +="<input type='text' class='layui-input search-field' id='"+ key +"' name='"+key+"' autocomplete='off' placeholder='请选择时间范围' fft='t_datetime' ffct='"+select.attr('ffct')+"'>";
			str +="<i class='fa fa-calendar icon_date_business'></i><a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			break;
		case 't_checkcondition'://复选框(查询时处于选中状态则该字段传值为1，未选中状态下不传值)
			var checkedStr = '';	
			if(select.attr('fieldDefault'))checkedStr = "checked";
			str +="<input type='checkbox' lay-skin='primary' class='search-field' id='"+ key +"' name='"+ key +"' fft='t_checkcondition' "+ checkedStr +"><a class='fa fa-times-circle-o remove-this' style='margin-top: 10px;'>&nbsp;</a></div></div>";
			break;
		case 't_buttontext'://弹出框
			str +="<input type='text' class='layui-input search-field buttontext' id='"+ key +"' name='"+ key +"' getType='"+ key +"'/>";
			str +="<i class='layui-icon layui-icon-more getMore' onclick=\"getMore(\'"+ key +"\',null,\'"+ select.attr('text') +"\',\'"+select.attr('fst')+"\');\"></i>";
			str += "<a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			break;
 		/*case 't_textarea'://文本区域
 			break;
			case 't_checkbox'://复选框
			break;
		case 't_decimal'://数值输入框
			break;*/
		case 't_radio'://单选按钮
			if(key == "userSexDA"){
				str += '<input type="radio" id="userSexDA" name="userSexDA" value="男" title="男" class="search-field" fft="t_radio"><input type="radio" name="userSexDA" value="女" title="女"></div>';
			}
			break;
		case 't_dropdown'://下拉框——html代码写在页面上
			str += $('#dropdown_'+key).text();
			str +="<a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			break;
		default://默认输入框
			str += "<input type='text' name='"+ key +"' id='"+key+"' autocomplete='off' class='layui-input search-field'><a class='fa fa-times-circle-o remove-this'>&nbsp;</a></div></div>";
			break;
	}
	$(obj).parents('.layui-form').find('.append-this').before(str);
	if(select.attr('fft')=='t_date'){//是日期则需要渲染
		if(select.attr('ffct')=='t_between')laydate.render({elem: '#'+key,type:'date',trigger:'click',range: '~'});
		else laydate.render({elem: '#'+key,type:'date',trigger:'click'});
	}
	if(select.attr('fft')=='t_month'){//是日期则需要渲染
		if(select.attr('ffct')=='t_between')laydate.render({elem: '#'+key,type:'date',trigger:'click',range: '~'});
		else laydate.render({elem: '#'+key,type:'month',trigger:'click'});
	}
	if(select.attr('fft')=='t_datetime'){//是日期则需要渲染
		if(select.attr('ffct')=='t_between')laydate.render({elem: '#'+key,type:'datetime',trigger:'click',range: '~'});
		else laydate.render({elem: '#'+key,type:'datetime',trigger:'click'});
	}
	form.render();
}
//键盘控制上下左右
document.onkeydown=function(event){
	var td_obj = $('.layui-table-edit').parent();
    var e = event || window.event || arguments.callee.caller.arguments[0];
	var data_field = td_obj.attr('data-field');
    if(e && e.keyCode==38){ // 上
    	var $nextTr = td_obj.parents('tr').prev();
        if($nextTr.length) {
            $nextTr.children('[data-field="'+data_field+'"]').trigger('click');
        }
    }
    if(e && e.keyCode==40){ //下
        var $nextTr = td_obj.parents('tr').next();
        if($nextTr.length) {
            $nextTr.children('[data-field="'+data_field+'"]').trigger('click');
        }
    }
    if(e && e.keyCode==37){ // 左
    	var $nextTr = td_obj.prev();
        if($nextTr.length) {
            $nextTr.trigger('click');
        }
    }
    if(e && e.keyCode==39 || e.keyCode === 13){ // 右
    	var $nextTr = td_obj.next();
        if($nextTr.length) {
            $nextTr.trigger('click');
        }
    }
}
//跳转指定链接
function goUrl(url){
	setTimeout(function(){
		window.location.href = url;
    }, 1000);
}
//数据表格下拉框赋值，dropdownList为下拉框field集合
function selectSelected(dropdownList){
	$.each(table.cache.dhtable,function(i,v){
		$.each(dropdownList,function(i2,v2){
			if(!!v[v2] && !!$('select[data-field='+v2+']').find("option[value='"+v[v2]+"']")[i])$('select[data-field='+v2+']').find("option[value="+v[v2]+"]")[i].selected=true;
		});
	});
	form.render();
}
//数据表格点击行时，添加背景颜色
$(document).on('click', '.layui-table-view .layui-table-body tr', function (event) {
	var trElem = $(this);
	var tableView = trElem.closest('.layui-table-view');
	tableView.find('.layui-table-body tr.table_tr_click').removeClass('table_tr_click');
	tableView.find('.layui-table-body tr[data-index="' + trElem.data('index') + '"]').addClass('table_tr_click');
})
//焦点在数据表格的输入控件时，触发点击行事件
$(document).on('focus', '.layui-table-view .layui-table-body input', function (event) {
	$(this).closest('tr').click();
})
//失去焦点方法
function inputOnBlur(obj){
	if($(obj).val().length < 1){
		obj.style.border='1px solid red';
  	}else{
  		obj.style.border='1px solid #e6e6e6';
  	}
}
//明细附件列表
function detailUpload(){
	$(".getDetailUpload").click(function(){
		var fileMark = $(this).attr("tGuid"),
			fieldName = $(this).attr("tName"),
			forObj = $(this).parent().find('input');
		
		var obj = $(this);
		getUpload(fieldName, "Detail", fileMark, forObj);
	})
}
/*
 * 获取单据附件列表
 * param:fieldName 附件字段名
 * param:vType 类型Head
 * param:fileMark 单据整单附件:nid、单据明细附件:guid、打印报表:moduletable值
 * param:forObj 赋值对象
 */
function getUpload(fieldName, vType="Head", fileMark="", forObj=""){
	var nid = $("#nid").val(),
		flag = true, forSet = '';
	if(vType == "Detail" && fileMark == "undefined"){
		flag = false;
		layer.msg("新增明细需保存单据后，才能上传附件！");
	}
	if(flag){
		if(nid != '0'){
			if(!fileMark)fileMark = nid;
			var mTitle = '附件列表', mUrl = '/system/fileinfo/add?moduleFile=attach&vType='+vType+'&fileMark='+fileMark+'&fieldName='+fieldName+'&moduleTable='+moduleTable, mWidth = '680', mHeight = '400';
		}else{
			flag = false;
			layer.msg("保存单据后，才能上传附件！");
		}
	    if(flag){
		    $.modal.openSimple(mTitle, mUrl, mWidth, mHeight, function(index){
		    	var res = window["layui-layer-iframe" + index].callbackdata();
		    	if(res){
		    		forSet = res+'个附件';
		    	}else{
		    		forSet = '无附件';
		    	}
		    	if(forObj){
		    		forObj.val(forSet)
		    	}else{
		    		$("#"+fieldName).val(forSet);
		    	}
	    		layer.close(index);
		    });
	    }
	}
}

function getReport(){
	var mTitle = '打印模板列表', mUrl = '/system/fileinfo/add?moduleFile=report&vType=Report&fileMark='+moduleTable+'&fieldName=Report&moduleTable='+moduleTable, mWidth = '680', mHeight = '400';
	$.modal.openSimple(mTitle, mUrl, mWidth, mHeight);
}
/*
 * 客户、供应商获取单据附件列表
 * param:fieldName 附件字段名
 * param:vType 类型Head
 * param:fileMark 客户、供应商编号
 * param:forObj 赋值对象
 */
function getUploadCommon(fieldName, vType="Head", fileMark="", forObj=""){
	var flag = true, forSet = '';
	if(flag){
		if(fileMark != null){
			var mTitle = '附件列表', mUrl = '/system/fileinfo/add?moduleFile=attach&vType='+vType+'&fileMark='+fileMark+'&fieldName='+fieldName+'&moduleTable='+moduleTable, mWidth = '680', mHeight = '400';
		}else{
			flag = false;
			layer.msg("保存后，才能上传附件！");
		}
	    if(flag){
		    $.modal.openSimple(mTitle, mUrl, mWidth, mHeight, function(index){
		    	var res = window["layui-layer-iframe" + index].callbackdata();
		    	if(res){
		    		forSet = res+'个附件';
		    	}else{
		    		forSet = '无附件';
		    	}
		    	if(forObj){
		    		forObj.val(forSet)
		    	}else{
		    		$("#"+fieldName).val(forSet);
		    	}
	    		layer.close(index);
		    });
	    }
	}
}
//JS函数用于获取url参数
function getQueryVariable(variable){
   var query = window.location.search.substring(1);
   var vars = query.split("&");
   for (var i=0;i<vars.length;i++) {
           var pair = vars[i].split("=");
           if(pair[0] == variable){return pair[1];}
   }
   return(false);
}